const {Router} = require('express');
const router = Router();
const mongo = require('../utils/mongo');

// 一、查
/* http://localhost:2003/api/goods?page=1&size=10&sort=sale_price,1 */
router.get('/', async (req,res)=>{
    // 处理参数
    let {page=1,size=5,sort='old_price'} = req.query;  // 注意不要用const定死，会报错
    const skip = (page-1)*size;
    const limit = size*1;
    sort = sort.split(',');
    // console.log(page,size,sort);

    // try/catch
    try{
        // 获取结果
        const result = await mongo.find('goods',{},{skip,limit,sort});
        // console.log(result.length);
        res.send({
            code:1,
            msg:'success',
            data:result
        });
    }catch(err){
        res.send({
            code:0,
            msg:'fail',
            data:[]
        });
    }
    
})

// 二、增
/* 
    * url:http://localhost:2003/api/goods
    * parameter
        + name:2019春季新款小白鞋男韩版板鞋男士白鞋百搭休闲鞋夏季增高男鞋子 白色 36
        + imgurl:https://www.nanshig.com/data/upload/shop/store/goods/47/47_06071111289163602_240.jpg
        + old_price:135.00
        + sale_price:89.00
*/
router.post('/',async(req,res)=>{
    // 1.获取参数
    let {name,imgurl,old_price,sale_price} = req.body;

    try{
        // 2.执行sql语句并获取结果
        const result = await mongo.insert('goods',{name:`${name}`,imgurl:`${imgurl}`,old_price:`${old_price}`,sale_price:`${sale_price}`})
        // 3.返回结果
        res.send({
            code:1,
            msg:'success',
            data:[]
        });
    }catch{
        res.send({
            code:0,
            msg:'fail',
            data:err
        });
    }
})


// 三、删：根据ID删除商品
/* http://localhost:2003/api/goods/5f30ce7d88410a4438a2cd0d */
router.delete('/:id',async(req,res)=>{
    // 1.获取参数
    const {id} = req.params;
    try{
        // 2.执行sql语句
        const result = await mongo.remove('goods',{_id:id});
        res.send({
            code:1,
            msg:'success',
            data:[]
        });
    }catch(err){
        res.send({
            code:0,
            msg:'fail',
            data:err
        });
    }
})

// 四、改：根据ID修改商品信息
/* 
    * url:http://localhost:2003/api/goods/5f3104dd34ff0428d8cd7faf
    * parameter
        + old_price:200.00
*/
router.put('/:id',async(req,res)=>{
    // 1.获取动态参数和请求体参数
    const {id} = req.params;
    const {old_price} = req.body;
    try{
        // 2.执行sql语句并返回前端结果
        const result = await mongo.update('goods',{_id:id},{$set:{old_price:old_price}});
        res.send({
            code:1,
            msg:'success',
            data:[]
        });
    }catch(err){
        res.send({
            code:0,
            msg:'fail',
            data:err
        });
    }
})

module.exports = router;
